package tms.util.context;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.InputStream;
import java.util.Set;

public class ApplicationContext implements ServletContainerInitializer {
    private static LoggingConfig loggingConfig;

    @Override
    public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
        loggingConfig = unmarshal(LoggingConfig.class, servletContext.getResourceAsStream(Config.LOGGING.file()));
    }

    public static LoggingConfig getLoggingConfig() {
        return loggingConfig;
    }


    @SuppressWarnings("unchecked")
    private <T> T unmarshal(Class<T> clazz, InputStream inputStream) {
        T retVal = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            retVal = (T)jaxbContext.createUnmarshaller().unmarshal(inputStream);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
        return retVal;
    }
}
